import React from 'react';
import { Bar } from 'react-chartjs-2';
import {
  Chart as ChartJS,
  CategoryScale,
  LinearScale,
  BarElement,
  Title,
  Tooltip,
  Legend
} from 'chart.js';

ChartJS.register(
  CategoryScale,
  LinearScale,
  BarElement,
  Title,
  Tooltip,
  Legend
);

export const TimeSpentChart = ({ timeSpentByDomain, limit = 10 }) => {
  const sortedDomains = Object.entries(timeSpentByDomain)
    .sort((a, b) => b[1].estimatedMinutes - a[1].estimatedMinutes)
    .slice(0, limit);

  const data = {
    labels: sortedDomains.map(([domain]) => domain.length > 20 ? domain.substring(0, 20) + '...' : domain),
    datasets: [
      {
        label: 'Estimated Minutes',
        data: sortedDomains.map(([, data]) => data.estimatedMinutes),
        backgroundColor: 'rgba(102, 126, 234, 0.8)',
        borderColor: 'rgba(102, 126, 234, 1)',
        borderWidth: 1
      }
    ]
  };

  const options = {
    responsive: true,
    maintainAspectRatio: false,
    plugins: {
      legend: {
        display: false
      },
      tooltip: {
        callbacks: {
          label: function(context) {
            const domain = sortedDomains[context.dataIndex][0];
            const visits = sortedDomains[context.dataIndex][1].visits;
            return `${context.parsed.y} min (${visits} visits)`;
          }
        }
      }
    },
    scales: {
      y: {
        beginAtZero: true,
        ticks: {
          color: 'rgba(255, 255, 255, 0.7)'
        },
        title: {
          display: true,
          text: 'Minutes',
          color: 'rgba(255, 255, 255, 0.7)'
        }
      },
      x: {
        ticks: {
          color: 'rgba(255, 255, 255, 0.7)',
          maxRotation: 45,
          minRotation: 45
        }
      }
    }
  };

  return (
    <div style={{ height: '300px', width: '100%' }}>
      <Bar data={data} options={options} />
    </div>
  );
};

